//
//  PasswordChangeViewController.m
//  WisdomZhuHai
//
//  Created by JasonLee on 15/1/29.
//  Copyright (c) 2015年 wyd. All rights reserved.
//

#import "PasswordChangeViewController.h"
#import "TransforController.h"
#import "ProtocolManager.h"

#define KEEP_PASSAWORD_LIST @"keepPassword.plst"
#define KEY_ACCOUNT @"key_account"
#define KEY_PASSWORD @"key_passord"
#define KEY_IFKEEPPASSWORD @"key_ifkeeppassord"
#define USER_INFO_LIST @"userinfo.text"
#define LOGINSTATUS @"loginStatus.plst"

@interface PasswordChangeViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property (nonatomic, strong) UITableView *view_table;
@property (nonatomic, strong) NSMutableArray *array_txt;
@property (strong, nonatomic) UITextField *txt_actived;

@end

@implementation PasswordChangeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setFrame:CGRectMake(0, 0, 320, 568)];
    UIView *view_navigationBar = [TransforController shardeInstanceOfNavigationBarAndStatusBarCoverViewWithY:0 andTitle:@"修改密码"];
    [self.view addSubview:view_navigationBar];
    self.view_table = [[UITableView alloc]initWithFrame:CGRectMake(0, 65, 320, 568 - 65) style:UITableViewStyleGrouped];
    self.view_table.delegate = self;
    self.view_table.dataSource = self;
    [self.view addSubview:self.view_table];
    
    self.array_txt = [[NSMutableArray alloc]init];
    
    UIBarButtonItem *btn_sendRequest = [[UIBarButtonItem alloc]initWithTitle:@"修改" style:UIBarButtonItemStyleDone target:self action:@selector(requestSendAction)];
    self.navigationItem.rightBarButtonItem = btn_sendRequest;
    
    UITapGestureRecognizer *defaultTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(defaultSingleTapAction:)];
    //设置手势属性
    defaultTapGestureRecognizer.numberOfTapsRequired = 1;//设置点按次数，默认为1，注意在iOS中很少用双击操作
    defaultTapGestureRecognizer.numberOfTouchesRequired = 1;//点按的手指数
    [self.view addGestureRecognizer:defaultTapGestureRecognizer];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(self.isChangeWithPhone){
        return 1;
    }else{
        return 2;
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSString *string_titleOfSection = nil;
    if(self.isChangeWithPhone){
        switch (section) {
            case 0:
                string_titleOfSection = @"新密码";
                break;
            case 1:
                string_titleOfSection = @"再次输入";
                break;
            default:
                break;
        }
    }else{
        switch (section) {
            case 0:
                string_titleOfSection = @"原密码";
                break;
            case 1:
                string_titleOfSection = @"新密码";
                break;
            case 2:
                string_titleOfSection = @"再次输入";
                break;
            default:
                break;
        }
    }
    return string_titleOfSection;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HotCommentsMiddle"];
    UITextField *txt_temp = [[UITextField alloc]initWithFrame:CGRectMake(20, 0, 280, 45)];
//    txt_temp.leftViewMode = UITextFieldViewModeAlways;
//    txt_temp.leftView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"输入框密码.png"]];
    txt_temp.secureTextEntry = YES;
    txt_temp.clearButtonMode = UITextFieldViewModeWhileEditing;
    txt_temp.delegate = self;
    [self.array_txt addObject:txt_temp];
//    NSLog(@"%s || array_txt:%@", __FUNCTION__, self.array_txt);
    [cell addSubview:txt_temp];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%s || indexPath:%d", __FUNCTION__, indexPath.row);


}

- (void)requestSendAction{
    NSLog(@"%s || Request's been actived and isChangeWithPhone:%hhd and array_text:%d", __FUNCTION__, self.isChangeWithPhone, [self.array_txt count]);
    if([ProtocolManager shareInstance].isLoginedByPhone){
        [[Common shareInstance]showAlertViewWithTitle:nil text:@"手机登陆无法修改密码" dismissTime:0.8];
        return;
    }
    NSMutableArray *array_temp = [[NSMutableArray alloc]init];
    for(UITextField *txt_temp in self.array_txt){
        if([txt_temp.text isEqualToString:@""]){
            [[Common shareInstance]showAlertViewWithTitle:nil text:@"请先填写密码" dismissTime:0.8];
            return;
        }
        [array_temp addObject:[NSString stringWithFormat:@"%@", txt_temp.text]];
    }
    NSLog(@"%s || array_temp:%@", __FUNCTION__, array_temp);
    if(self.isChangeWithPhone){
        NSString *string_new = [NSString stringWithString:array_temp[0]];
        if(![TransforController validatePassword:string_new]){
            [[Common shareInstance]showAlertViewWithTitle:nil text:@"密码格式不正确" dismissTime:0.8];
            return;
        }
        [[ProtocolManager shareInstance]sendChangePasswordWithNew:string_new andMobile:self.string_mobile andTarget:self andSelector:@selector(sendChangePasswordCallBack:)];
        [TransforController umengEvent:@"PasswordForget" attributes:@{@"With" : @"Mobile phone", @"attr":@"no record"} number:@(1) ct:@"900004"];
    }else{
        NSString *string_new = [NSString stringWithString:array_temp[1]];
        NSString *string_old = [NSString stringWithString:array_temp[0]];
        if(![TransforController validatePassword:string_new]){
            [[Common shareInstance]showAlertViewWithTitle:nil text:@"新密码格式不正确" dismissTime:0.8];
            return;
        }
        if(![TransforController validatePassword:string_old]){
            [[Common shareInstance]showAlertViewWithTitle:nil text:@"原密码格式不正确" dismissTime:0.8];
            return;
        }
        [[ProtocolManager shareInstance]sendChangePasswordWithOld:string_old andNewPassword:string_new andLoginName:[ProtocolManager shareInstance].loginName andTarget:self andSelector:@selector(sendChangePasswordCallBack:)];
    }
}

- (void)sendChangePasswordCallBack:(NSDictionary *) dic{
    NSLog(@"%s || dic:%@", __FUNCTION__, dic);
    if(dic == nil){
        return;
    }
    if([[Common valueForKey:@"respCode" dic:dic]isEqualToString:@"000"]){
        [[Common shareInstance]showAlertViewWithTitle:nil text:@"密码修改成功" dismissTime:0.8];
        UITextField *txt_temp = self.array_txt[1];
        NSMutableDictionary *savingDic = [NSMutableDictionary dictionary];
        //[savingDic setValue:[dic objectForKey:P_SID] forKey:P_SID];
//        [savingDic setValue:[ProtocolManager shareInstance].loginName forKey:@"loginName"];
        [savingDic setValue:[NSString stringWithFormat:@"%d", [ProtocolManager shareInstance].userId] forKey:P_USERID];
        [savingDic setValue:[ProtocolManager shareInstance].loginName forKey:@"loginName"];
        [savingDic setValue:txt_temp.text forKey:KEY_PASSWORD];
        [savingDic setValue:[ProtocolManager shareInstance].username forKey:@"Username"];
        [savingDic setValue:[ProtocolManager shareInstance].mobile forKey:P_MOBILENUMBER];
        [savingDic setValue:@"0001" forKey:@"LoginStatus"];
        [savingDic writeToFile:[FileManager getFullDocumentPath:LOGINSTATUS]atomically:YES];
        [self.navigationController popToRootViewControllerAnimated:YES];
    } else if([[Common valueForKey:@"respCode" dic:dic]isEqualToString:@"901"]){
        [[Common shareInstance]showAlertViewWithTitle:nil text:@"原密码不正确" dismissTime:0.8];
    }else{
        [[Common shareInstance]showAlertViewWithTitle:nil text:@"密码修改失败" dismissTime:0.8];
    }
}

- (void)defaultSingleTapAction:(UITapGestureRecognizer *)gesture{
    for(UITextField *txt_temp in self.array_txt){
        [txt_temp resignFirstResponder];
    }
    NSLog(@"%s || action's been actived.", __FUNCTION__);
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.txt_actived = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    self.txt_actived = nil;
}

-(void)viewWillAppear:(BOOL)animated{
    [self registerForKeyboardNotifications];
}

-(void)viewWillDisappear:(BOOL)animated{
    [self removeForKeyboardNotifications];
}

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)removeForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    //    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    //    self.view_scroll_temp.contentInset = contentInsets;
    //    self.view_scroll_temp.scrollIndicatorInsets = contentInsets;
    
    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your application might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= (kbSize.height + 20);
    CGRect rect_txt_actived = self.txt_actived.superview.frame;
    if ((rect_txt_actived.origin.y + rect_txt_actived.size.height) > aRect.size.height) {
        CGPoint scrollPoint = CGPointMake(0.0, self.view.frame.size.height - kbSize.height - self.txt_actived.superview.frame.size.height * 2);
        [self.view_table setContentOffset:scrollPoint animated:YES];
        self.view_table.scrollEnabled = NO;
    }
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    //    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    //    self.view_scroll_temp.contentInset = contentInsets;
    //    self.view_scroll_temp.scrollIndicatorInsets = contentInsets;
    
    [self.view_table setContentOffset:CGPointMake(0, 0) animated:YES];
    self.view_table.scrollEnabled = YES;
}


@end
